import { Injectable, BadRequestException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { UserEntity } from '@/database/entities'
import { SignInDTO, SignUpDTO } from './dtos'
import { JwtPayload } from './jwt.payload'

@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>
  ) {}

  /**
   * 秘钥签名
   * @param {SignInDTO} data 登录数据
   * @returns {Promise<string>} 秘钥签名
   */
  async sign(data: SignInDTO): Promise<string> {
    const { username, password } = data
    const exsitingUser = await this.userRepository.findOne({ username })

    if (exsitingUser) {
      const isMatch = exsitingUser.password === password

      if (isMatch) {
        return this.jwtService.sign({ username, sub: exsitingUser.userId })
      }

      throw new BadRequestException('用户名或密码错误')
    }

    throw new BadRequestException('用户不存在')
  }

  /**
   * 校验用户
   * @param {JwtPayload} payload 载荷
   * @returns {Promise<UserEntity>} 用户
   */
  async validateUser(payload: JwtPayload): Promise<UserEntity> {
    const { username } = payload
    return await this.userRepository.findOne({ username })
  }

  /**
   * 创建用户
   * @param {SignUpDTO} data 注册数据
   */
  async createUser(data: SignUpDTO): Promise<void> {
    const { username } = data
    const exsitingUser = await this.userRepository.findOne({ username })

    if (exsitingUser) {
      throw new BadRequestException('用户已存在')
    }

    await this.userRepository.save(data)
  }
}
